package com.ganzalang.gmall.gmallfreemarker.util;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.ganzalang.gmall.gmallfreemarker.api.dto.UserDTO;
import com.ganzalang.gmall.gmallfreemarker.exception.BusinessException;
import com.ganzalang.gmall.gmallfreemarker.properties.JwtProps;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;

/**
 * 单点登录：https://developer.aliyun.com/article/985710
 */
@Slf4j
@Component
public class JwtUtil {

    public static final String BEARER_KEY = "Bearer ";
    @Resource
    private JwtProps jwtProps;

    /**
     * 生成token
     *
     * @param userDTO
     * @param jwtId
     * @return
     */
    public String createJwt(UserDTO userDTO, String jwtId) {
        String token = JWT.create()
                .withIssuer(jwtProps.getIssuer())
                .withIssuedAt(new Date())
                .withJWTId(jwtId)
                .withAudience(JSON.toJSONString(userDTO))
                .sign(Algorithm.HMAC256(jwtProps.getSecret()));
        return BEARER_KEY + token;
    }

    public DecodedJWT verifyJwt(String token) {
        try {
            return JWT.require(Algorithm.HMAC256(jwtProps.getSecret()))
                    .withIssuer(jwtProps.getIssuer())
                    .build()
                    .verify(token);
        } catch (JWTVerificationException e) {
            log.error("token:{}, 校验失败", token, e);
            throw BusinessException.VERIFY_TOKEN_ERROR;
        }
    }
}

